package demo

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
	"github.com/google/uuid"
)

// ReplacingMergeTree 示例

type FileMetadata struct {
	FileID            uuid.UUID
	FirstSeen         time.Time
	LastSeen          time.Time
	Sha256            string
	RiskScore         uint8
	RiskFactors       []string
	MalwareType       *string
	MalwareFamily     *string
	IsMalicious       *bool
	AnalysisStatus    string
	AnalysisTimestamp *time.Time
	Version           uint32
}

// 插入两条version不同，file_id相同的数据
func insertFileMetadataData(conn driver.Conn) (uuid.UUID, error) {
	query := `
		INSERT INTO file_metadata (
			file_id, first_seen, last_seen, sha256, risk_score, 
			risk_factors, malware_type, malware_family, is_malicious, 
			analysis_status, analysis_timestamp, version
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	`

	// 生成相同的file_id用于测试
	fileID := uuid.New()
	now := time.Now()

	// 插入第一条数据 version=1
	err := conn.Exec(context.Background(), query,
		fileID,
		now,
		now,
		"abc123def456",
		80,
		[]string{"suspicious", "obfuscated"},
		"trojan",
		"agent_tesla",
		true,
		"analyzed",
		&now,
		1,
	)
	if err != nil {
		return uuid.Nil, fmt.Errorf("failed to insert first record: %w", err)
	}

	// 插入第二条数据 version=2 (相同file_id但版本更高)
	later := now.Add(time.Hour)
	err = conn.Exec(context.Background(), query,
		fileID,
		now,
		later,
		"abc123def456",
		90,
		[]string{"suspicious", "obfuscated", "malicious"},
		"trojan",
		"agent_tesla_v2",
		true,
		"analyzed",
		&later,
		2,
	)
	if err != nil {
		return uuid.Nil, fmt.Errorf("failed to insert second record: %w", err)
	}

	fmt.Println("Successfully inserted two records with different versions")
	return fileID, nil
}

// 根据 file_id 查询数据，确认是否去重
func queryFileMetadata(conn driver.Conn, fileID uuid.UUID) (*FileMetadata, error) {
	query := `
		SELECT 
			file_id, first_seen, last_seen, sha256, risk_score, 
			risk_factors, malware_type, malware_family, is_malicious, 
			analysis_status, analysis_timestamp, version
		FROM file_metadata 
		ORDER version desc
		WHERE file_id = ?
	`

	var metadata FileMetadata
	err := conn.QueryRow(context.Background(), query, fileID).Scan(
		&metadata.FileID,
		&metadata.FirstSeen,
		&metadata.LastSeen,
		&metadata.Sha256,
		&metadata.RiskScore,
		&metadata.RiskFactors,
		&metadata.MalwareType,
		&metadata.MalwareFamily,
		&metadata.IsMalicious,
		&metadata.AnalysisStatus,
		&metadata.AnalysisTimestamp,
		&metadata.Version,
	)
	if err != nil {
		return nil, fmt.Errorf("failed to query record: %w", err)
	}

	return &metadata, nil
}

func RunReplacingMergeTreeDemo(conn driver.Conn) {
	// 测试连接
	if err := conn.Ping(context.Background()); err != nil {
		log.Fatal(err)
	}

	// 插入测试数据
	// fileID, err := insertFileMetadataData(conn)
	// if err != nil {
	// 	log.Fatal(err)
	// }

	// if fileID == uuid.Nil {
	// 	log.Fatal("fileID is nil")
	// }

	// // 等待后台合并完成（实际使用中可能需要手动触发optimize）
	// time.Sleep(2 * time.Second)

	fileID, _ := uuid.Parse("96db1ef9-53dd-45a1-aec5-20bcef0b641a")

	// 查询数据验证去重效果
	// 这里我们查询特定的file_id，应该只返回version最高的那条记录
	data, err := queryFileMetadata(conn, fileID)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Query result for file_id %s, %s, %s, %s, %d:\n",
		data.FileID,
		data.FirstSeen.Format("2006-01-02 15:04:05"),
		data.LastSeen.Format("2006-01-02 15:04:05"),
		*data.MalwareFamily,
		data.Version)
	// 在实际应用中，应使用已知的fileID进行查询
}
